package com.hdu.dwh.validators;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.hdu.dwh.pojos.model_pojos.MetaTable;
import com.hdu.dwh.pojos.source_access_pojos.DataWarehouseDatabase;
import com.hdu.dwh.pojos.source_access_pojos.DataWarehouseTable;
import com.hdu.dwh.service.DataWarehouseDatabaseService;
import com.hdu.dwh.service.DataWarehouseTableService;

@Component
public class MetaTableValidator implements Validator {

    @Autowired
    private DataWarehouseTableService tableService;

    @Autowired
    private DataWarehouseDatabaseService databaseService;

    @Override
    public boolean supports(Class<?> clazz) {
        return MetaTable.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        MetaTable metaTable = (MetaTable) target;
        if(metaTable.getSourceTableId() == null) {
            errors.rejectValue("sourceTableId", "MetaTable.sourceTableId.null", "源表ID不能为空");
        }
        DataWarehouseTable table = tableService.getById(metaTable.getSourceTableId());
        if(table == null) {
            errors.rejectValue("sourceTableId", "MetaTable.sourceTableId.notExist", "源表不存在");
            return;
        }
        DataWarehouseDatabase db = databaseService.getById(table.getDatabaseId());
        if(db == null) {
            errors.rejectValue("sourceTableId", "MetaTable.sourceTableId.dbNotExist", "源表对应的数据库不存在");
            return;
        }
        if(!db.getSourceType().equals("paimon")) {
            errors.rejectValue("sourceTableId", "MetaTable.sourceTableId.dbNotPaimon", "源表对应的数据库不是Paimon类型");
            return;
        }
        
    }
    
}
